package com.laizhenghua.example.controller;

import com.laizhenghua.example.configuration.QueryParamDTO;
import com.laizhenghua.example.dao.UserDao;
import com.laizhenghua.example.service.UserService;
import com.laizhenghua.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @description:
 * @date: 2022/4/26 22:15
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    public R getUserList() {

        return R.ok().put("data", userDao.findAll());
    }

    /**
     * Excel导入数据接口
     * @param file
     * @return
     */
    @RequestMapping(value = "/excel/import", method = RequestMethod.POST)
    public R importData(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "filePath") String filePath,
            @RequestParam(value = "fileName") String fileName,
            @RequestParam(value = "configName") String configName) {
        QueryParamDTO queryParam = new QueryParamDTO();
        queryParam.setFilePath(filePath);
        queryParam.setFileName(fileName);
        queryParam.setConfigName(configName);
        Map<String, String> result = userService.importExcelData(file, queryParam);
        String error = result.get("error");
        if (error != null) {
            return R.error(500, error);
        }
        return R.ok().put("data", result);
    }

    /**
     * Excel导出数据接口
     * @param response
     * @return
     */
    @RequestMapping(value = "/excel/export", method = RequestMethod.GET)
    @CrossOrigin(origins = "*")
    public void exportData2(@RequestParam(value = "filePath") String filePath, @RequestParam(value = "fileName") String fileName,
                            @RequestParam(value = "configName") String configName, HttpServletResponse response) {
        QueryParamDTO queryParam = new QueryParamDTO();
        queryParam.setFilePath(filePath);
        queryParam.setFileName(fileName);
        queryParam.setConfigName(configName);
        userService.exportData(queryParam, response);
    }
}
